<?php

class ProductController extends AController {

    public function loadModel($id) {
        $model = DProduct::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    public function actions() {
        return array(
            'sortOrder' => array(
                'class'        => 'ext.mylib.widgets.OrderColumn.OrderAction',
                'modelClass'   => 'DProduct',
            ),
            'toggleActive' => array(
                'class'      => 'ext.mylib.widgets.ActiveColumn.ActiveAction',
                'modelClass' => 'DProduct',
            ),
            'upload' => array(
                'class'     => 'ext.actions.upload.PlUploadProduct',
                'file_name' => 'file_upload',
                'params'    => Yii::app()->params['product'],
            ),
        );
    }

    public function init() {
        parent::init();
        SpsState::setPrefix('DProduct');
    }

    public function actionIndex() {
        if (Yii::app()->request->isAjaxRequest) {
            SpsState::writeState('DProduct');
        }

        $model = new DProduct('search');
        $model->unsetAttributes();  // clear any default values

        if (isset($_GET['DProduct']))
            $model->attributes = $_GET['DProduct'];
        elseif (SpsState::hasState('search'))
            $model->attributes = SpsState::getState('search');

        $this->render('index', array(
            'model' => $model,
        ));
    }

    public function actionCreate() {
        $model = new DProduct;

        if (isset($_POST['DProduct'])) {
            $model->attributes = $_POST['DProduct'];

            if ($model->save()) {
                Yii::app()->user->setFlash('message', 'created');
                $this->redirect(array('index'));
            }
        } else {
            $session = Yii::app()->user->getState($model->params['plupload_session']);
            if (isset($session['small'])) $model->file1 = $session['small']['file_name'];
            if (isset($session['normal'])) $model->file2 = $session['normal']['file_name'];
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionUpdate($id) {
        Yii::app()->user->setFlash('keepState', true);
        $model = $this->loadModel($id);

        if (isset($_POST['DProduct'])) {
            $model->attributes = $_POST['DProduct'];
            if ($model->save()) {
                Yii::app()->user->setFlash('message', 'updated');
                $this->redirect(array('index'));
            }
        } else {
            $model->setDefaultValue();
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    public function actionDelete($id) {
        if (Yii::app()->request->isAjaxRequest) {
            $this->loadModel($id)->delete();
            $result['success'] = true;
            echo json_encode($result);
        } else {
            throw new CHttpException(400, 'Invalid request');
        }
    }

    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'product-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function actionCancel() {
        $this->detectAjaxRequest();
        $model = new DProduct();
        $model->clearSession();
    }
    
    public function actionCropImage() {
        $model = new DProduct();
        $session = Yii::app()->user->getState($model->params['plupload_session']);
        $file = $session['normal']['file_name'];
        
        if (isset($_POST['crop_info'])) {
            $fileCropped = $model->cropImage($file, $_POST['crop_info'], $session);
            
            //write $_SESSION
            $session['small']['file_name'] = $session['small']['thumb_name'] = $fileCropped;
            Yii::app()->user->setState($model->params['plupload_session'], $session);
            
            echo $fileCropped;
            Yii::app()->end();
        } else {
            $this->layout = '//layouts/admin/main_none';
            $this->render('_crop_image', array(
                'model' => $model,
                'file'  => $file,
            ));
        }
    }
    
    private function detectAjaxRequest() {
        if (! Yii::app()->request->isAjaxRequest) {
            throw new CHttpException('403', 'Forbidden');
            Yii::app()->end();
        }
    }
}